<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 85%;overflow-y: hidden">

    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form"  v-bind="layout"  :model="model" :rules="validatorRules">
        <a-form-model-item label="任务名称" required prop="taskName">
          <a-input v-model="model.taskName" placeholder="请输入任务名称"/>
        </a-form-model-item>
        <a-form-model-item label="任务类型" prop="taskType">
          <j-dict-select-tag @change="onTaskChange" type="list" placeholder="请选择任务类型" v-model="model.taskType"
                             dictCode="task_type"></j-dict-select-tag>
        </a-form-model-item >
        <a-form-model-item v-if="model.taskType==0||model.taskType==2"  label="参数" prop="parameter">
          <a-textarea placeholder="请输入参数" :rows="1" :autosize="{ minRows: 1, maxRows: 100 }" v-model="model.parameter" />
        </a-form-model-item>

        <el-divider v-if="model.taskType==1" content-position="left">爬虫信息</el-divider>

        <a-form-model-item v-if="model.taskType==1" label="网站"  prop="websiteId">
          <a-select
            v-model="model.websiteId"
            filterable
            allowClear
            default-first-option
            show-search
            optionFilterProp="label"
            @change="change"
            placeholder="请选择网站">
            <a-select-option
              v-for="item in data3"
              :key="item.id"
              :value="Number(item.id)"
              :label="item.name">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item v-if="model.taskType==1" label="文章"  prop="docIds">
          <a-select
            v-model="model.docIds"
            mode="multiple"
            filterable
            allowClear
            default-first-option
            show-search
            optionFilterProp="label"
            placeholder="请选择文章">
            <a-select-option
              v-for="item in data4"
              :key="item.id"
              :value="Number(item.id)"
              :label="item.name">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item v-if="model.taskType==1" label="知识库"  prop="knowledgeBase">
          <a-select  v-model="model.knowledgeBase"
                     filterable
                     allowClear
                     default-first-option
                     placeholder="请选择知识库"
          >
            <a-select-option
              v-for="item in data5"
              :key="item.id"
              :value="item.roleName">
              {{ item.roleName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>


        <a-form-model-item label="描述" prop="description">
          <a-textarea placeholder="请输入描述" :rows="1" :autosize="{ minRows: 1, maxRows: 100 }" v-model="model.description" />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
  import {addIndexTask,editIndexTask,duplicateCheck } from '@/api/api'
  import { httpAction,getAction } from '@/api/manage'

  export default {
    name: "IndexTaskModal",
    data () {
      return {
        title:"操作",
        CrawlId: '',
        visible: false,
        roleDisabled: false,
        data3: [],
        data4: [],
        data5: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model: {},
        layout: {
          labelCol: { span: 3 },
          wrapperCol: { span: 14 },
        },
        confirmLoading: false,
        validatorRules:{
          taskName: [
            {validator: this.validateWorkNo},
            { required: true, message: '请输入任务名称!' }
          ],
          taskType: [
            { required: true, message: '请选择任务类型!' },
          ],
          websiteId:[
            {required: true, message: '请选择网站!'}
          ],
          knowledgeBase:[
            {required: true, message: '请选择知识库!'}
          ],
          parameter: [
            { required: true, message: '参数不能为空!' },
          ]
        },
        url: {
          list3: "/sys/CrawlWebsite/list",
          list4: "/sys/CrawlSiteFeatureDocCont/list",
          list5:  '/sys/knowledgebase/list',
        },
      }
    },

    created () {
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.loadData3();
      this.loadData4();
    },
    methods: {

      onTaskChange(value) {
        this.$set(this.model, 'websiteId',undefined);
        this.$set(this.model, 'docIds',[]);
        this.$set(this.model, 'knowledgeBase',undefined);
        this.data4=[];
        console.log('=====Selected value===========:'+ value);
      },

      change(value) {
        this.$set(this.model, 'docIds',[]);
        this.CrawlId = value
        this.getFeatureDocList();
      },

      getFeatureDocList(){
        console.log("========this.CrawlId=======" + JSON.stringify(this.CrawlId))
        if (this.CrawlId!=undefined&&this.CrawlId!=null){
          let params = {}
          params.websiteId = this.CrawlId
          getAction(this.url.list4, params).then((res) => {
            if (res.success) {
              this.data4 = res.result.records
            }
          })
        } else {
          this.data4=[];
        }
      },

      loadData3() {
        let params = {}
        getAction(this.url.list3, params).then((res) => {
          console.log("========res========" + JSON.stringify(res))
          if (res.success) {
            this.data3 = res.result.records
          }
        })
      },
      loadData4() {
        let params = {}
        getAction(this.url.list5, params).then((res) => {
          if (res.success) {
            this.data5 = res.result.records
          }
        })
      },

      add () {
        this.modelDefault
        console.log("========新增========"+JSON.stringify(this.modelDefault))
        this.edit({
          a:'add'
        });
      },
      edit (record) {
        this.model = Object.assign({}, record);
        if (this.model.a!="add"&&this.model.taskType==1){
          var modelJson = JSON.parse(this.model.parameter);
          console.log("========modelJson========" + JSON.stringify(modelJson))
          this.CrawlId = modelJson.crawl_params.website_id;
          if (this.CrawlId!=undefined && this.CrawlId!=null) {
            this.getFeatureDocList();
            this.$set(this.model, 'websiteId', modelJson.crawl_params.website_id);
            this.$set(this.model, 'docIds', modelJson.crawl_params.doc_ids);
            this.$set(this.model, 'knowledgeBase', modelJson.job_params.kb);
          }else {
            this.$set(this.model, 'websiteId',undefined);
            this.$set(this.model, 'docIds',[]);
            this.$set(this.model, 'knowledgeBase',undefined);
          }
        }
        this.visible = true;
        //编辑页面禁止修改角色编码
        if(this.model.id){
          this.roleDisabled = true;
        }else{
          this.roleDisabled = false;
        }
      },
      close () {
        this.$refs.form.clearValidate();
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let obj;
            if(!this.model.id){
              console.log('--------提交参数------',this.model)
              obj=addIndexTask(this.model);
            }else{
              obj=editIndexTask(this.model);
            }
            obj.then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }else{
            return false;
          }
        })
      },
      handleCancel () {
        this.close()
      },
      validateWorkNo(rule, value, callback){
        let params = {
          tableName: 'sys_index_task',
          fieldName: 'task_name',
          fieldVal: value,
          dataId: this.model.id,
        };
        duplicateCheck(params).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback("任务名称重复!")
          }
        })
      },

    }
  }
</script>

<style scoped>

</style>
